package org.nokatag.code;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.FilterConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.noka.cookie.CookieUtil;
import org.nokatag.system.BugInfoWrint;
import org.nokatag.system.Concest;

public class ImageOutRequest {
	
	public static void outImage(HttpServletRequest request,HttpServletResponse response,FilterConfig config){
		try {
			OutputStream out = response.getOutputStream();
			ImageOut imgout = new ImageOut();
			Random rnd = new Random();
	        Integer counterp = rnd.nextInt(4); 
			String FontColor = (request.getParameter("FontColor")==null?"255, 0, 0":request.getParameter("FontColor"));
			Integer Length = Integer.parseInt(request.getParameter("Length")==null?"4":request.getParameter("Length")); //验证码长度
			Integer Height = Integer.parseInt(request.getParameter("Height")==null?"60":request.getParameter("Height"));//高
			Integer Width = Integer.parseInt(request.getParameter("Width")==null?"160":request.getParameter("Width"));//宽
			Integer MaxSize=Integer.parseInt(request.getParameter("MaxSize")==null?"45":request.getParameter("MaxSize"));   //字体最大
			Integer MinSize=Integer.parseInt(request.getParameter("MinSize")==null?"40":request.getParameter("MinSize"));//字体最小
			Integer counter=Integer.parseInt(request.getParameter("counter")==null?String.valueOf(counterp):request.getParameter("counter"));//干绕方式
			String codename = (request.getParameter("codename")==null?"noka_code":request.getParameter("codename"));//验证码在session里面的名字
			Integer kword=Integer.parseInt(request.getParameter("kword")==null?"1":request.getParameter("kword"));//验证码
			imgout.setCounter(counter);
			imgout.setFontColor(FontColor);
			imgout.setHeight(Height);
			imgout.setLength(Length);
			imgout.setMaxSize(MaxSize);
			imgout.setMinSize(MinSize);
			imgout.setWidth(Width);
			imgout.setKword(Concest.KWORD_CONFIG.get("kword_"+kword)==null?"":Concest.KWORD_CONFIG.get("kword_"+kword));
			BufferedImage bimg = imgout.CreateImage();
			CookieUtil cutil = new CookieUtil();
			cutil.setCookie(response,codename,imgout.getWord().toLowerCase());//设置cookies
			ImageIO.write(bimg, "png",out); 
			out.flush();
			out.close();
			BugInfoWrint.Print("验证码："+imgout.getWord().toLowerCase());
			request.getSession().setAttribute(codename,imgout.getWord().toLowerCase());
		} catch (IOException e) {
			BugInfoWrint.Print(e);
		}
	}
}
